package spring;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author yhy
 * @date 17-7-11
 */
public class SpringContainerMain implements Runnable {
	private static final Logger LOGGER = LoggerFactory.getLogger(SpringContainerMain.class);
	/**
	 * 找指定的XML配置文件，找到并装载完成ApplicationContext的实例化工作
	 */
	private static ClassPathXmlApplicationContext context = null;

	/**
	 * 多线程通信的结束信号
	 */
	private static Object waitTerm = new Object();

	/**
	 * 获取spring应用上下文
	 *
	 * @return spring应用上下文
	 */
	public static ClassPathXmlApplicationContext getContext() {
		return context;
	}

	/**
	 * 启动 spring 容器,并注册结束时候调用 stop()
	 */
	public void start(String configPath) {
		context = new ClassPathXmlApplicationContext(configPath);
		context.start();
	}

	/**
	 * 关闭 spring 容器
	 */
	public void stop() {
		try {
			if (context != null) {
				context.stop();
				context.close();
				context = null;
			}
		} catch (Throwable throwable) {
			LOGGER.error(throwable.toString(), throwable);
		}

	}


	/**
	 * 阻塞等待结束信号
	 */
	public void waitTerminalSignal() {
		//==========开启子线程等待 SIGINT 和 SIGTERM 信号======
		Runtime.getRuntime().addShutdownHook(new Thread(this));
		//==========主线程等待结束信号========================
		synchronized (waitTerm) {
			try {
				waitTerm.wait();
				LOGGER.info("=====================main concurrent {} recv sig to stop===============", Thread.currentThread().getId());
			} catch (InterruptedException e) {
				e.printStackTrace();
				LOGGER.error("{}", e.toString());
			}
		}
	}


	@Override
	public void run() {
		try {
			synchronized (waitTerm) {
				waitTerm.notify();
				LOGGER.info("===================concurrent {} recv sig  SIGINT/SIGTERM, notify main concurrent to stop===================", Thread.currentThread().getId());
			}
		} catch (Throwable var6) {
			LOGGER.info("spring exit error: {}", var6.getMessage());
		}

	}


	/**
	 * 	////////////////////////主函数////////////////////////////
	 */
//	public static void main(String args[]) {
//		try {
//			final SpringContainerMain springContainer = new SpringContainerMain();
//			springContainer.start("spring-application.xml");
//			springContainer.waitTerminalSignal();
//			springContainer.stop();
//		} catch (Exception e) {
//			e.printStackTrace();
//			LOGGER.error("{}", e.toString());
//		}
//	}
}
